
package com.shop.cloud.weixin.admin.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.shop.cloud.common.core.util.FileUtils;
import com.shop.cloud.common.core.util.R;
import com.shop.cloud.common.log.annotation.SysLog;
import com.shop.cloud.weixin.admin.config.open.WxComponentConfigProperties;
import com.shop.cloud.weixin.admin.config.open.WxOpenConfiguration;
import com.shop.cloud.weixin.common.constant.WxReturnCode;
import com.shop.cloud.weixin.common.entity.WxAuthAudit;
import com.shop.cloud.weixin.admin.service.WxAuthAuditService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.bean.CommonUploadData;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.open.api.WxOpenMaAuthService;
import me.chanjar.weixin.open.bean.auth.MaAuthUploadResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.security.access.prepost.PreAuthorize;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Operation;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * 小程序认证审核
 *
 * @author
 * @date 2024-05-24 10:13:09
 */
@Slf4j
@RestController
@AllArgsConstructor
@RequestMapping("/wxauthaudit")
@Tag(description = "wxauthaudit", name = "小程序认证审核管理")
public class WxAuthAuditController {

    private final WxAuthAuditService wxAuthAuditService;
    private final WxComponentConfigProperties wxComponentConfigProperties;

    /**
     * 小程序认证审核分页列表
     * @param page 分页对象
     * @param wxAuthAudit 小程序认证审核
     * @return
     */
    @Operation(summary = "小程序认证审核分页列表")
    @GetMapping("/page")
    @PreAuthorize("@ato.hasAuthority('wxma:wxauthaudit:index')")
    public R getPage(Page page, WxAuthAudit wxAuthAudit) {
        return R.ok(wxAuthAuditService.page(page, Wrappers.query(wxAuthAudit)));
    }

    /**
     * 小程序认证审核查询
     * @param id
     * @return R
     */
    @Operation(summary = "小程序认证审核查询")
    @GetMapping("/{id}")
    @PreAuthorize("@ato.hasAuthority('wxma:wxauthaudit:index')")
    public R getById(@PathVariable("id") String id) {
        return R.ok(wxAuthAuditService.getById(id));
    }

    /**
     * 小程序认证审核新增
     * @param wxAuthAudit 小程序认证审核
     * @return R
     */
    @Operation(summary = "小程序认证审核新增")
    @SysLog("新增小程序认证审核")
    @PostMapping
    @PreAuthorize("@ato.hasAuthority('wxma:wxauthaudit:index')")
    public R save(@RequestBody WxAuthAudit wxAuthAudit) {
        wxAuthAudit.setTaskStatus(null);
        wxAuthAuditService.save(wxAuthAudit);
        return R.ok(wxAuthAudit);
    }

    /**
     * 小程序认证审核修改
     * @param wxAuthAudit 小程序认证审核
     * @return R
     */
    @Operation(summary = "小程序认证审核修改")
    @SysLog("修改小程序认证审核")
    @PutMapping
    @PreAuthorize("@ato.hasAuthority('wxma:wxauthaudit:index')")
    public R updateById(@RequestBody WxAuthAudit wxAuthAudit) {
        return R.ok(wxAuthAuditService.updateById(wxAuthAudit));
    }

    /**
     * 小程序认证审核删除
     * @param id
     * @return R
     */
    @Operation(summary = "小程序认证审核删除")
    @SysLog("删除小程序认证审核")
    @DeleteMapping("/{id}")
    @PreAuthorize("@ato.hasAuthority('wxma:wxauthaudit:index')")
    public R removeById(@PathVariable String id) {
        return R.ok(wxAuthAuditService.removeById(id));
    }

    /**
     * 提交小程序认证审核
     * @param id
     * @return
     */
    @Operation(summary = "提交小程序认证审核")
    @SysLog("提交小程序认证审核")
    @PostMapping("/sub/{id}")
    @PreAuthorize("@ato.hasAuthority('wxma:wxauthaudit:index')")
    public R sub(@PathVariable("id") String id) {
        WxAuthAudit wxAuthAudit = wxAuthAuditService.getById(id);
        Map<String, Object> map = new HashMap<>();
        Map<String, Object> mapAuthData = BeanUtil.beanToMap(wxAuthAudit.getAuthData());
        mapAuthData.put("third_party_phone", wxComponentConfigProperties.getPhone());
        map.put("auth_data", mapAuthData);
        try {
            String responseContent = WxOpenConfiguration.getOpenService().getWxOpenComponentService().getWxMaServiceByAppid(wxAuthAudit.getAppId()).post("https://api.weixin.qq.com/wxa/sec/wxaauth", map);
            JSONObject jsonObject = JSONUtil.parseObj(responseContent);
            String errCode = jsonObject.getStr("errcode");
            if(WxReturnCode.SUC_0.getCode().equals(errCode)){
                String authUrl = jsonObject.getStr("auth_url");
                String taskId = jsonObject.getStr("taskid");
                wxAuthAudit.setAuthUrl(authUrl);
                wxAuthAudit.setTaskId(taskId);
                wxAuthAudit.setTaskStatus("0");
                //更新小程序管理员授权链接
                wxAuthAuditService.updateById(wxAuthAudit);
                return R.ok();
            }else {
                return R.failed(jsonObject.getStr("errmsg"));
            }
        } catch (WxErrorException e) {
            e.printStackTrace();
            return WxReturnCode.wxErrorExceptionHandler(e);
        }
    }

    /**
     * 重新提交小程序认证审核
     * @param id
     * @return
     */
    @Operation(summary = "重新提交小程序认证审核")
    @SysLog("重新提交小程序认证审核")
    @PostMapping("/resub/{id}")
    @PreAuthorize("@ato.hasAuthority('wxma:wxauthaudit:index')")
    public R reSub(@PathVariable("id") String id) {
        WxAuthAudit wxAuthAudit = wxAuthAuditService.getById(id);
        Map<String, Object> map = new HashMap<>();
        Map<String, Object> mapAuthData = BeanUtil.beanToMap(wxAuthAudit.getAuthData());
        mapAuthData.put("taskid", wxAuthAudit.getTaskId());
        mapAuthData.put("third_party_phone", wxComponentConfigProperties.getPhone());
        map.put("auth_data", mapAuthData);
        try {
            String responseContent = WxOpenConfiguration.getOpenService().getWxOpenComponentService().getWxMaServiceByAppid(wxAuthAudit.getAppId()).post("https://api.weixin.qq.com/wxa/sec/reauth", map);
            JSONObject jsonObject = JSONUtil.parseObj(responseContent);
            String errCode = jsonObject.getStr("errcode");
            if(WxReturnCode.SUC_0.getCode().equals(errCode)){
                String authUrl = jsonObject.getStr("auth_url");
                if(StrUtil.isNotBlank(authUrl)){
                    wxAuthAudit.setAuthUrl(authUrl);
                }
                wxAuthAudit.setTaskStatus("0");
                //更新小程序管理员授权链接
                wxAuthAuditService.updateById(wxAuthAudit);
                return R.ok();
            }else {
                return R.failed(jsonObject.getStr("errmsg"));
            }
        } catch (WxErrorException e) {
            e.printStackTrace();
            return WxReturnCode.wxErrorExceptionHandler(e);
        }
    }

    /**
     * 小程序认证上传补充材料
     * @param mulFile
     * @param appId
     * @return
     * @throws IOException
     */
    @Operation(summary = "小程序认证上传补充材料")
    @PostMapping("/uploadauthmaterial/{appid}")
    public R imageUploadV3(@RequestParam("file") MultipartFile mulFile, @PathVariable("appid") String appId) throws IOException {
        File file = FileUtils.multipartFileToFile(mulFile);
        try {
            CommonUploadData commonUploadData = new CommonUploadData();
            commonUploadData.setInputStream(FileUtil.getInputStream(file));
            commonUploadData.setFileName(file.getName());
            commonUploadData.setLength(file.length());
            WxOpenMaAuthService wxOpenMaAuthService = WxOpenConfiguration.getOpenService().getWxOpenComponentService().getWxMaServiceByAppid(appId).getAuthService();
            MaAuthUploadResult maAuthUploadResult = wxOpenMaAuthService.upload(commonUploadData);
            return R.ok(maAuthUploadResult);
        } catch (WxErrorException e) {
            e.printStackTrace();
            return WxReturnCode.wxErrorExceptionHandler(e);
        }
    }
}
